package de.slothsoft.commons.swing.window;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;

import de.slothsoft.commons.res.CommonImages;
import de.slothsoft.commons.res.CommonMessages;
import de.slothsoft.commons.swing.AboutPanel.AboutInfo;
import de.slothsoft.commons.swing.JToolBarManager;

public abstract class AbstractApplet extends JApplet {

	private static final long serialVersionUID = 1L;

	// TODO: this and AbstractMainFrame are to similar

	private static AbstractApplet instance;

	public AbstractApplet() {
		instance = this;
		setLookAndFeel();
		createMainPanel();
	}

	protected void setLookAndFeel() {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			throw new RuntimeException("Could not set look and feel: " + UIManager.getSystemLookAndFeelClassName());
		}
	}

	private void createMainPanel() {
		setLayout(new BorderLayout());

		Component toolbar = createToolbar();
		if (toolbar != null) {
			add(toolbar, BorderLayout.NORTH);
		}

		Component component = createComponents();
		if (component != null) {
			add(component, BorderLayout.CENTER);
		}
	}

	protected Component createToolbar() {
		if (!hasToolbar() && !hasAboutToolbar()) {
			return null;
		}

		JPanel parent = new JPanel();
		parent.setLayout(new BorderLayout());

		if (hasToolbar()) {
			JToolBarManager manager = new JToolBarManager();
			manager.getToolBar().setFloatable(false);
			createToolbar(manager);
			parent.add(manager.getToolBar(), BorderLayout.CENTER);
		} else {
			parent.add(new JLabel(), BorderLayout.CENTER);
		}

		if (hasAboutToolbar()) {
			JToolBarManager aboutManager = new JToolBarManager();
			aboutManager.getToolBar().setFloatable(false);
			aboutManager.add(CommonImages.get(CommonImages.TOOLBAR_ABOUT),
					CommonMessages.getString("AboutDialog.toolbarButton"), new ActionListener() {//$NON-NLS-1$

						@Override
						public void actionPerformed(ActionEvent e) {
							performAbout();
						}
					});
			parent.add(aboutManager.getToolBar(), BorderLayout.EAST);
		}

		return parent;
	}

	protected void performAbout() {
		AboutDialog dialog = new AboutDialog(null, createAboutInfo());
		dialog.open();
	}

	protected abstract AboutInfo createAboutInfo();

	protected boolean hasAboutToolbar() {
		return true; // to be overridden
	}

	protected boolean hasToolbar() {
		return false; // to be overridden
	}

	protected void createToolbar(JToolBarManager manager) {
		// to be overridden
	}

	// must be overriden

	protected abstract Component createComponents();

	public static AbstractApplet getInstance() {
		return instance;
	}
}
